<template>
  <el-form
    :model="passForm"
    :rules="rules"
    ref="passFormRef"
    label-width="100px"
  >
    <el-form-item label="原密码" prop="oldPass">
      <el-input
        type="password"
        v-model="passForm.oldPass"
        clearable
        show-password
      ></el-input>
    </el-form-item>
    <el-form-item label="新密码" prop="newPass">
      <el-input
        type="password"
        v-model="passForm.newPass"
        clearable
        show-password
      ></el-input>
    </el-form-item>
    <el-form-item label="确认密码" prop="checkPass">
      <el-input
        type="password"
        v-model="passForm.checkPass"
        clearable
        show-password
      ></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="modifyPass">立即修改</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { mapMutations } from "vuex";
export default {
  data() {
    return {
      passForm: {
        oldPass: "",
        newPass: "",
        checkPass: "",
      },
      rules: {
        oldPass: [{ required: true, message: "请输入原密码", trigger: "blur" }],
        newPass: [
          { required: true, message: "请输入新密码", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (value === this.passForm.oldPass) {
                callback(new Error("新密码不能与原密码"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        checkPass: [
          { required: true, message: "请输入确认密码", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (value !== this.passForm.newPass) {
                callback(new Error("密码不一致"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    ...mapMutations(["clearUser"]),

    // 修改密码
    modifyPass() {
      this.$refs.passFormRef.validate(async (valid) => {
        if (valid) {
          let { data } = await this.$axios({
            method: "POST",
            url: "/personal/modifyPass",
            data: {
              oldPass: this.passForm.oldPass,
              newPass: this.passForm.newPass,
            },
          });
          if (data.code) return this.$message.error(data.message);
          this.$message.success(data.message); //提示
          this.clearUser(); //清空vuex里的数据
          this.$refs.passFormRef.resetFields(); //清空表单
          this.$router.push("/"); //跳转到/路由下  编程式导航
        } else {
          return false;
        }
      });
    },
  },
};
</script>

<style>
</style>